package com.android.phoenix.bluetooth;

import com.android.phoenix.Constant;
import com.android.phoenix.MainApplication;
import com.android.phoenix.R;
import com.android.phoenix.activity.SportActivity;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.app.Service;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

public class BluetoothConnectActivity extends Activity {
	private ImageView title_Imgbtn_left_up;
	private TextView title_txt_center;
	private TextView txtBluTitle;	
	private ImageView imgSearch;
	private Animator currentAnimation;
	private CircularProgressDrawable drawable;
	private CommandReceiver receiver;
	private String bluAdress;
	private ListView listDevice;
	private BluDeviceListAdapter bluDeviceListAdapter;
	private LinearLayout layoutTips;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.acti_blutooth_connect);
		//获取数据
		getData();
		// 初始化一些控�
		initView();
		// 初始化titleBar
		initTitleBar();
		//start BluetoothService
		begainServer();
		
	}
	private void getData()
	{
		bluAdress = MainApplication.mSharedPreferences.getString(Constant.BLUTOOTHDEVICE, null);
	}
	ServiceConnection conn = new ServiceConnection()
	{
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			// TODO Auto-generated method stub
		}
		@Override
		public void onServiceDisconnected(ComponentName name) {
			// TODO Auto-generated method stub
		}		
	};
	/**
	 * @Aaron.create-method:begainServer
	 * @date:2015/1/28
	 */
	private void begainServer()
	{
		Intent intent =  this.getIntent();
		intent.putExtra("Device", bluAdress);
		intent.setClass(this, BluetoothService.class);
		startService(intent);	
		receiver= new CommandReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(BluetoothService.ACTION_CMD_DEVICE_CONNECTED);
		filter.addAction(BluetoothService.ACTION_CMD_DEVICE_DISCONNECTED);
		filter.addAction(BluetoothService.ACTION_CMD_DEVICE_DISCOVERING);
		filter.addAction(BluetoothDevice.ACTION_FOUND);
		registerReceiver(receiver, filter);
	}
	/**
	 * 
	 * @Title: initTitleBar
	 * @Description: TODO(设置统一的titleBar)
	 * @author: wWX230766
	 * @date: 2015-1-6 下午10:00:48
	 */
	private void initTitleBar() {
		title_Imgbtn_left_up = (ImageView) this
				.findViewById(R.id.title_Imgbtn_left_up);
		title_txt_center = (TextView) this.findViewById(R.id.title_txt_center);
		title_txt_center.setText(R.string.label_blutooth_connect);
		title_Imgbtn_left_up.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent it = new Intent();
				it.setClass(BluetoothConnectActivity.this, SportActivity.class);
				startActivity(it);
				finish();
			}
		});
	}
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		drawable = new CircularProgressDrawable.Builder()
        .setRingWidth(getResources().getDimensionPixelSize(R.dimen.drawable_ring_size))
        .setOutlineColor(getResources().getColor(android.R.color.darker_gray))
        .setRingColor(getResources().getColor(android.R.color.holo_green_light))
        .setCenterColor(getResources().getColor(R.color.blue))
        .create();
		imgSearch.setImageDrawable(drawable);
		currentAnimation = prepareStyle1Animation();
		currentAnimation.start();
	}
	private void initView()
	{
	    txtBluTitle  = (TextView)findViewById(R.id.txtBluTitle);		
		layoutTips = (LinearLayout)findViewById(R.id.layoutTips);
		imgSearch = (ImageView)findViewById(R.id.imgSearch);
		listDevice = (ListView)findViewById(R.id.list_blutooth_device);
		if(null == bluAdress)
		{
			txtBluTitle.setText(getString(R.string.connecting));
		}
	}
	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {	
			String bluDevice = ((BluetoothDevice)msg.getData().getParcelable("Device")).getAddress();
			MainApplication.mSharedPreferences.edit().putString(Constant.BLUTOOTHDEVICE, bluDevice).commit();
			Intent intent = new Intent();
			intent.putExtra("Device", bluDevice);
			intent.setAction(BluetoothService.ACTION_CMD_SEND_DEVICE);
			sendBroadcast(intent);
		};
	};
	  @Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		unregisterReceiver(receiver);
	}
	/**
     * Style 1 animation will simulate a indeterminate loading while taking advantage of the inner
     * circle to provide a progress sense
     *
     * @return Animation
     */
    private Animator prepareStyle1Animation() {
        AnimatorSet animation = new AnimatorSet();

        final Animator indeterminateAnimation = ObjectAnimator.ofFloat(drawable, CircularProgressDrawable.PROGRESS_PROPERTY, 0, 12000);
        indeterminateAnimation.setDuration(12000);

        Animator innerCircleAnimation = ObjectAnimator.ofFloat(drawable, CircularProgressDrawable.CIRCLE_SCALE_PROPERTY, 0f, 0.75f);
        innerCircleAnimation.setDuration(12000);
        innerCircleAnimation.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                drawable.setIndeterminate(true);
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                indeterminateAnimation.end();
                drawable.setIndeterminate(false);
                drawable.setProgress(0);
            }
        });
        animation.playTogether(innerCircleAnimation, indeterminateAnimation);
        return animation;
    }

    private class CommandReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
        	if(intent.getAction().equals(BluetoothService.ACTION_CMD_DEVICE_CONNECTED))
        	{
//        		intent.setClass(BluetoothConnectActivity.this,BluConnectFinishActivity.class);
//        	   	startActivity(intent);
        	}else if(intent.getAction().equals(BluetoothService.ACTION_CMD_DEVICE_DISCONNECTED))
        	{
        	  intent.setClass(BluetoothConnectActivity.this,BluConnectFailActivity.class);
          	  startActivity(intent);
        	}else if(intent.getAction().equals(BluetoothService.ACTION_CMD_DEVICE_DISCOVERING))
        	{
        	  listDevice.setVisibility(View.VISIBLE);
          	  layoutTips.setVisibility(View.GONE);
          	   bluDeviceListAdapter = new BluDeviceListAdapter(BluetoothConnectActivity.this,handler);
        	  listDevice.setAdapter(bluDeviceListAdapter);
        	}
        	else if(intent.getAction().equals(BluetoothDevice.ACTION_FOUND))
        	{
        		 BluetoothDevice device = (BluetoothDevice)intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
   	            // Add the name and address to an adapter to show in a ListView
   	             bluDeviceListAdapter.add(device);
        	}
        }                        
    }
}
